import axios from './axios';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

// 数据结构节点类型
export interface StructureNode {
  id: string;
  name: string;
  type?: string;
  description?: string;
  parentId?: string | null;
  required?: boolean;
  level?: number;
  children?: StructureNode[];
  [key: string]: any;
}

// 获取数据结构配置
export const getDataStructure = async (): Promise<StructureNode[]> => {
  try {
    const response = await axios.get(
      `${API_BASE_URL}/-/bin.systemManagement.get_data_structure`
    );
    return response.data.data || [];
  } catch (error) {
    console.error('获取数据结构配置失败:', error);
    // 如果接口不可用，返回空数组
    return [];
  }
};

// 保存数据结构配置
export const saveDataStructure = async (data: StructureNode[]): Promise<boolean> => {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/-/bin.systemManagement.save_data_structure`,
      { data }
    );
    return response.data.code === 0;
  } catch (error) {
    console.error('保存数据结构配置失败:', error);
    return false;
  }
};

// 将Excel解析后的数据上传到服务器
export const uploadExcelData = async (data: any[]): Promise<{
  success: boolean;
  data?: StructureNode[];
  message?: string;
}> => {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/-/bin.systemManagement.upload_excel_data`,
      { data }
    );
    
    if (response.data.code === 0) {
      return {
        success: true,
        data: response.data.data || []
      };
    } else {
      return {
        success: false,
        message: response.data.message || '上传失败'
      };
    }
  } catch (error) {
    console.error('上传Excel数据失败:', error);
    return {
      success: false,
      message: '服务请求异常'
    };
  }
};

// 获取系统运行状态
export interface SystemStatus {
  cpuUsage: number;
  memoryUsage: number;
  diskUsage: number;
  runningTime: string;
  lastStartTime: string;
  version: string;
}

export const getSystemStatus = async (): Promise<SystemStatus> => {
  try {
    const response = await axios.get(
      `${API_BASE_URL}/-/bin.systemManagement.get_system_status`
    );
    return response.data.data || {
      cpuUsage: 0,
      memoryUsage: 0,
      diskUsage: 0,
      runningTime: '0',
      lastStartTime: '-',
      version: '1.0.0'
    };
  } catch (error) {
    console.error('获取系统状态失败:', error);
    // 返回默认值
    return {
      cpuUsage: 0,
      memoryUsage: 0,
      diskUsage: 0,
      runningTime: '0',
      lastStartTime: '-',
      version: '1.0.0'
    };
  }
}; 